<?php

declare(strict_types=1);

namespace Modules\Cms\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Cms\Models\Category;
use Modules\Cms\Models\Post;

class PostController extends Controller
{
    public function __construct(
        protected readonly Post $model
    ) {
    }

    /**
     * @return mixed
     */
    public function index(): mixed
    {
        return $this->model->setBeforeGetList(function ($query) {
            return $query->select($this->model->aliasField('id'), 'title', $this->model->aliasField('status'), 'is_can_comment', 'order', 'top', $this->model->aliasField('updated_at'), 'admin_users.username as creator')
                ->leftJoin('admin_users', 'admin_users.id', '=', $this->model->getTable().'.author')
                ->addSelect([
                    'category' => Category::whereColumn('id', $this->model->getTable().'.category_id')->select(DB::raw('name'))->limit(1),
                ]);
        })->getList();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        return $this->model->storeBy($request->all());
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function show($id)
    {
        $post = $this->model->firstBy($id);

        $post->tags = $post->tags()->get()->pluck('name');

        return $post;
    }

    /**
     * @param $id
     * @param Request $request
     * @return true
     */
    public function update($id, Request $request)
    {
        if ($this->model->updateBy($id, $request->all())) {
            $this->model->savePostTags($this->model->firstBy($id));
        }

        return true;
    }

    /**
     * 删除
     */
    public function destroy($id): bool
    {
        return $this->model->deletesBy($id);
    }

    /**
     * enable
     */
    public function enable($id): bool
    {
        return $this->model->togglesBy($id);
    }
}
